﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace TwoPageView3 {
    class FolderTreeViewRootFolderModel {
        List<FolderTreeViewItemViewModel> mDrives = new List<FolderTreeViewItemViewModel>();

        public FolderTreeViewRootFolderModel() {
            UpdateDriveList();
        }

        private void UpdateDriveList() {
            try {
                var existDrives = new List<FolderTreeViewItemViewModel>();
                string[] drives = System.IO.Directory.GetLogicalDrives();
                foreach (string drive in drives) {
                    var itemSearch = from FolderTreeViewItemViewModel item in mDrives
                                     where String.Compare(item.ActualName as string, drive) == 0
                                     select item;
                    var itemEnumerator = itemSearch.GetEnumerator();

                    if (!itemEnumerator.MoveNext()) {
                        // Tree does not contain this drive. Add.
                        if (drive.Length < 2) {
                            // root directory on UNIX... IGNORE
                            continue;
                        }
                        var item = new FolderTreeViewItemViewModel(drive.TrimEnd('\\'), drive, null);
                        if (item.DirectoryInfo == null) {
                            continue;
                        }
                        mDrives.Add(item);
                        existDrives.Add(item);
                    } else {
                        existDrives.Add(itemEnumerator.Current);
                    }
                }

                var disappearedDrives = new List<FolderTreeViewItemViewModel>();
                foreach (var item in mDrives) {
                    if (!existDrives.Contains(item)) {
                        disappearedDrives.Add(item);
                    }
                }
                foreach (var item in disappearedDrives) {
                    mDrives.Remove(item);
                }
            } catch (System.IO.IOException) {
            } catch (Exception ex) {
                System.Console.WriteLine(ex);
            }
        }

        public IList<FolderTreeViewItemViewModel> Drives {
            get { return mDrives; }
        }

    }
}
